package com.designPatterns.singleton;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 有上限多例模式
 * 若需要固定数目的实例,如两个实例在内存中,可以使用如下的方法
 * Created by houjinxin on 16/3/5.
 */
public class LimitNumberInstance {

    private static List<LimitNumberInstance> instances = new ArrayList<>();

    private static int countNumOfInstance = 0;

    private static final int maxInstanceCount = 2;

    static {
        for (int i = 0; i < maxInstanceCount; i++) {
            instances.add(new LimitNumberInstance(i));
        }
    }

    private LimitNumberInstance() {
    }

    private LimitNumberInstance(int flag) {
        System.out.println("我是限制实例数目的类" + flag);
    }

    public static LimitNumberInstance getInstance(){
        Random r = new Random();
        countNumOfInstance = r.nextInt(maxInstanceCount);
        return instances.get(countNumOfInstance);
    }

    /**
     * 该方法用于测试随机获取实例,但获取的实例在一定范围内
     */
    public static void doSomething(){
        System.out.println("当前实例编号: " + countNumOfInstance);
    }

}
